package com.ruoyi.system.service.impl;

import java.security.NoSuchAlgorithmException;
import java.util.List;

import com.alibaba.nacos.common.utils.MD5Utils;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.domain.PDealerLogin;
import com.ruoyi.system.domain.PFileInfo;
import com.ruoyi.system.domain.dto.PDealerDto;
import com.ruoyi.system.domain.vo.PDealerVo;
import com.ruoyi.system.mapper.PFileInfoMapper;
import com.ruoyi.system.service.IPDealerLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.PDealerMapper;
import com.ruoyi.system.domain.PDealer;
import com.ruoyi.system.service.IPDealerService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 经销商Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-01-28
 */
@Service
public class PDealerServiceImpl implements IPDealerService 
{
    @Autowired
    private PDealerMapper pDealerMapper;
    @Autowired
    private IPDealerLoginService pDealerLoginService;
    @Autowired
    private PFileInfoMapper pFileInfoMapper;

    /**
     * 查询经销商
     * 
     * @param id 经销商主键
     * @return 经销商
     */
    @Override
    public PDealerVo selectPDealerById(Long id)
    {
        return pDealerMapper.selectPDealerVoById(id);
    }

    /**
     * 查询经销商列表
     * 
     * @param pDealer 经销商
     * @return 经销商
     */
    @Override
    public List<PDealerVo> selectPDealerList(PDealer pDealer)
    {
        return pDealerMapper.selectPDealerVoList(pDealer);
    }

    /**
     * 新增经销商
     * 
     * @param pDealer 经销商
     * @return 结果
     */
    @Transactional
    @Override
    public int insertPDealer(PDealerDto pDealer) throws Exception {
        PDealer con = new PDealer();
        con.setDealerName(pDealer.getDealerName());
        if(pDealerMapper.selectPDealerList(con).size() >= 1){
            throw new Exception("该经销商名称已经存在，不允许重复的经销商名称");
        }

        con = new PDealer();
        con.setDistrict(pDealer.getDistrict());
        //县级经销商只能由两个经销商
        if(pDealerMapper.selectPDealerList(con).size() == 2){
            throw new Exception("县级只允许有两个经销商，不允许添加更多");
        }
        Long parentId = pDealer.getParentId();
        pDealer.setCreateTime(DateUtils.getNowDate());
        pDealer.setCreateBy(SecurityUtils.getUsername());
        pDealer.setUpdateTime(DateUtils.getNowDate());
        pDealer.setUpdateBy(SecurityUtils.getUsername());
        int num = pDealerMapper.insertPDealer(pDealer);

        if(num == 0){
            return 0;
        }
        if(parentId != null){
            PDealer parent = pDealerMapper.selectPDealerById(parentId);
            pDealer.setAncestors(parent.getAncestors()+","+pDealer.getId());
        }else{
            pDealer.setAncestors(pDealer.getId()+"");
            pDealer.setParentId(pDealer.getId());
        }
        pDealerMapper.updatePDealer(pDealer);
        //初始化一个经销商账号密码
        PDealerLogin pDealerLogin = new PDealerLogin();
        pDealerLogin.setDealerId(pDealer.getId());
        pDealerLogin.setLoginName(pDealer.getPhone());//默认账号
        pDealerLogin.setPassword(MD5Utils.md5Hex("123456"+pDealer.getPhone(),"utf-8"));//默认密码
        num = pDealerLoginService.insertPDealerLogin(pDealerLogin);
        PFileInfo pFileInfo = pFileInfoMapper.selectPFileInfoById(pDealer.getFileId());
        if (pFileInfo != null){
            pFileInfo.setDelFlag("0");
            pFileInfo.setContactTable("p_dealer");
            pFileInfo.setContactId(pDealer.getId());
            pFileInfoMapper.updatePFileInfo(pFileInfo);
        }
        return num;
    }


    /**
     * 修改经销商
     * 
     * @param pDealer 经销商
     * @return 结果
     */
    @Override
    public int updatePDealer(PDealerDto pDealer) throws Exception {
        PDealer con = new PDealer();
        con.setDealerName(pDealer.getDealerName());
        List<PDealer> selectPDealerList = pDealerMapper.selectPDealerList(con);
        boolean b = selectPDealerList.get(0).getId() != pDealer.getId();
        if(selectPDealerList != null && selectPDealerList.size() >= 1 && Long.compare(selectPDealerList.get(0).getId(), pDealer.getId()) != 0){
            throw new Exception("该经销商名称已经存在，不允许重复的经销商名称");
        }
        pDealer.setUpdateBy(SecurityUtils.getUsername());
        pDealer.setUpdateTime(DateUtils.getNowDate());
        int i = pDealerMapper.updatePDealer(pDealer);
        PFileInfo confile = new PFileInfo();
        confile.setContactId(pDealer.getId());
        confile.setContactTable("p_school");
        confile.setDelFlag("0");
        List<PFileInfo> pFileInfos = pFileInfoMapper.selectPFileInfoList(confile);
        if (!CollectionUtils.isEmpty(pFileInfos)&& pFileInfos.get(0).getId() != pDealer.getFileId()){
            PFileInfo pFileInfo = pFileInfos.get(0);
            pFileInfo.setDelFlag("1");
            pFileInfoMapper.updatePFileInfo(pFileInfo);
            pFileInfo = pFileInfoMapper.selectPFileInfoById(pDealer.getFileId());
            pFileInfo.setContactId(pDealer.getId());
            pFileInfo.setContactTable("p_dealer");
            pFileInfoMapper.updatePFileInfo(pFileInfo);
        }else if(CollectionUtils.isEmpty(pFileInfos)){
            PFileInfo  pFileInfo = pFileInfoMapper.selectPFileInfoById(pDealer.getFileId());
            pFileInfo.setContactId(pDealer.getId());
            pFileInfo.setContactTable("p_dealer");
            pFileInfo.setDelFlag("0");
            pFileInfoMapper.updatePFileInfo(pFileInfo);
        }
        return i;
    }

    /**
     * 批量删除经销商
     * 
     * @param ids 需要删除的经销商主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deletePDealerByIds(Long[] ids)
    {
        for(int i = 0; i < ids.length; i++) {
            PDealer pDealer = new PDealer();
            pDealer.setId(ids[i]);
            pDealer.setDelFlag("1");
            pDealerMapper.updatePDealer(pDealer);
            PFileInfo pFileInfo = pFileInfoMapper.selectPFileInfoById(ids[i]);
            pFileInfo.setDelFlag("1");
            pFileInfoMapper.updatePFileInfo(pFileInfo);
        }
        return ids.length;
    }

    /**
     * 删除经销商信息
     * 
     * @param id 经销商主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deletePDealerById(Long id)
    {
        PDealer pDealer = new PDealer();
        pDealer.setId(id);
        pDealer.setDelFlag("1");
        pDealerMapper.updatePDealer(pDealer);
        return 1;
    }
}
